<template>
  <div class="gauge-chart-wrapper">
    <div ref="gaugeChart" class="chart-container"></div>
    <div v-if="loading" class="chart-loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载中...</span>
    </div>
  </div>
</template>

<script setup>
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import * as echarts from 'echarts'
import { Loading } from '@element-plus/icons-vue'

const props = defineProps({
  // 图表标题
  title: {
    type: String,
    default: ''
  },
  // 数据值（0-100）
  value: {
    type: Number,
    default: 0
  },
  // 图表高度
  height: {
    type: String,
    default: '300px'
  },
  // 自定义颜色
  colors: {
    type: Array,
    default: () => [
      [0.2, '#67c23a'],
      [0.8, '#e6a23c'],
      [1, '#f56c6c']
    ]
  },
  // 动画效果
  animation: {
    type: Boolean,
    default: true
  },
  // 仪表盘类型：progress(进度型), pointer(指针型)
  type: {
    type: String,
    default: 'pointer',
    validator: (value) => ['progress', 'pointer'].includes(value)
  }
})

const gaugeChart = ref(null)
let chartInstance = null
const loading = ref(false)

// 初始化图表配置
const getOption = () => {
  const baseOption = {
    title: props.title ? {
      text: props.title,
      left: 'center',
      top: '5%',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333'
      }
    } : null,
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: 100,
        splitNumber: 10,
        center: ['50%', '75%'],
        radius: '90%',
        axisLine: {
          lineStyle: {
            width: 30,
            color: props.colors
          }
        },
        pointer: {
          show: props.type === 'pointer',
          length: '75%',
          width: 8,
          itemStyle: {
            color: 'auto'
          }
        },
        axisTick: {
          distance: -30,
          length: 8,
          lineStyle: {
            color: '#fff',
            width: 2
          }
        },
        splitLine: {
          distance: -30,
          length: 30,
          lineStyle: {
            color: '#fff',
            width: 4
          }
        },
        axisLabel: {
          distance: 20,
          color: '#999',
          fontSize: 14
        },
        detail: {
          valueAnimation: true,
          formatter: '{value}%',
          color: 'auto',
          fontSize: 30,
          fontWeight: 'bold',
          offsetCenter: [0, props.type === 'pointer' ? '-20%' : '0%']
        },
        data: [
          {
            value: props.value
          }
        ]
      }
    ]
  }

  // 进度型仪表盘特殊配置
  if (props.type === 'progress') {
    baseOption.series[0].progress = {
      show: true,
      width: 30
    }
    baseOption.series[0].axisLine.lineStyle.width = 30
  }

  return baseOption
}

// 初始化图表
const initChart = () => {
  if (!gaugeChart.value) return

  // 如果实例已存在，先销毁
  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(gaugeChart.value)
  chartInstance.setOption(getOption())

  // 添加窗口大小改变监听
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小改变
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 监听数值变化
watch(() => props.value, (newVal) => {
  if (chartInstance) {
    chartInstance.setOption({
      series: [
        {
          data: [{ value: newVal }]
        }
      ]
    })
  }
})

onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

onUnmounted(() => {
  if (chartInstance) {
    window.removeEventListener('resize', handleResize)
    chartInstance.dispose()
    chartInstance = null
  }
})

// 暴露刷新方法
defineExpose({
  getInstance: () => chartInstance
})
</script>

<style scoped lang="scss">
.gauge-chart-wrapper {
  position: relative;
  width: 100%;
  height: v-bind(height);

  .chart-container {
    width: 100%;
    height: 100%;
  }

  .chart-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    color: #999;
    font-size: 14px;

    .el-icon {
      font-size: 32px;
    }
  }
}
</style>

